﻿using MaterialDesignThemes.Wpf;

using PLCS.App.Shared.Service;
using PLCS.Application.Contracts.StationApp.Dtos;
using PLCS.Application.Contracts.TrayApp.Dtos;

using Volo.Abp.ObjectMapping;

namespace PLCS.App.EquipmentManager.ViewModels.Tray;

public class TrayDetailViewModel : HostDialogViewModel
{
    private readonly IObjectMapper<EquipmentManagerModule> _objectMapper;
    private readonly IStationService _stationService;
    private readonly ITrayService _trayService;
    private TrayDto _model;
    private string _hintMessage;
    private bool _isEdit;

    public string HintMessage
    {
        get { return _hintMessage; }
        set { SetProperty(ref _hintMessage, value); }
    }

    public TrayDto Model
    {
        get { return _model; }
        set { SetProperty(ref _model, value); }
    }

    public bool IsEdit
    {
        get { return _isEdit; }
        set { SetProperty(ref _isEdit, value); }
    }

    public DelegateCommand TrayBindCommand { get; }

    public TrayDetailViewModel(IObjectMapper<EquipmentManagerModule> objectMapper, IStationService stationService, ITrayService trayService)
    {
        _objectMapper = objectMapper;
        _stationService = stationService;
        _trayService = trayService;
        TrayBindCommand = new DelegateCommand(TrayBind);
    }

    protected override async void Save()
    {
        try
        {
            SavebuttonIsEnabled = false;
            var tray = _objectMapper.Map<TrayDto, TrayEditDto>(Model);
            if (Model.Id != Guid.Empty)
                await _trayService.UpdateAsync(tray);
            else
                await _trayService.CreateAsync(tray);

            ShowMessage("操作成功");
            base.Save();
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
        finally { SavebuttonIsEnabled = true; }
    }

    private async void TrayBind()
    {
        try
        {
            await _trayService.TrayBindAsync(Model);
            HintMessage = "绑定成功";
            DialogHost.Close(IdentifierName, new DialogResult(ButtonResult.OK));
        }
        catch (Exception ex)
        {
            HintMessage = ex.Message;
        }
    }

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        if (parameters.ContainsKey("Value"))
        {
            Model = parameters.GetValue<TrayDto>("Value");
            Title = "编辑";
            IsEdit = true;
        }
        else
        {
            Title = "新增";
            Model = new TrayDto();
            IsEdit = false;
        }
    }
}